#!/bin/bash
# shebang行
# 提示信息
echo "This is log_info.sh"
# 设置nginx的日志文件路径
logfiel_path='/var/log/nginx/access.log'
# 声明函数
Get_http_status()
{
	#从日志文件中获取访问状态码并记录输出
	http_status_codes=$(cat /var/log/nginx/access.log | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}" | awk '{
        	if($2>=100&&$2<200)
                	{i++}
        	if($2>=200&&$2<300)
               		{j++}
        	if($2>=300&&$2<400)
                	{k++}
        	if($2>=400&&$2<500)
                	{m++}
        	if($2>=500)
                	{n++}
	}END{print i?i:0,j?j:0,k?k:0,m?m:0,n?n:0,i+j+k+m+n}')
	# 声明数组
	declare -a http_status_code
	# 将获取的数据转换为数组
	http_status_code=($http_status_codes)
	# 输出对应的状态码次数
	echo -e "The counter http status[100+]: " ${http_status_code[0]}
	echo -e "The counter http status[200+]: " ${http_status_code[1]}
	echo -e "The counter http status[300+]: " ${http_status_code[2]}
	echo -e "The counter http status[400+]: " ${http_status_code[3]}
	echo -e "The counter http status[500+]: " ${http_status_code[4]}
	echo -e "The counter http status[ALL]: " ${http_status_code[5]}

}
# 声明函数
Get_http_codes()
{
	# 从日志文件中获取状态码的信息
	http_codes=$(cat /var/log/nginx/access.log | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}" | awk -v total=0 '{
         if($2!="")
                {code[$2]++;total++}
                else
                        {exit}
                }END{print code[404]?code[404]:0,code[500]?code[500]:0,total}')
	# 声明数组
        declare -a http_code
	# 将获取的信息转换为数组
        http_code=($http_codes)
	# 输出获取的信息
        echo -e "The Counter of 404: " ${http_code[0]}
        echo -e "The Counter of 500: " ${http_code[1]}
        echo -e "The Counter of ALL Request: " ${http_code[2]}

}
# 调用函数
Get_http_status
Get_http_codes
